<?php
/**
 * 退款订单管理
 * User: lxq
 * Date: 2018/4/24
 * Time: 9:16
 */
class order_refundControl  extends  SystemControl {
    private $links = array(
        array('url'=>'act=order_refund&op=index','lang'=>'nc_manage')
    );

    public function __construct()
    {
        parent::__construct();
        Language::read('order');
    }

    /**
     * 订单列表
     */
    public function indexOp()
    {
        /* @var order_refundModel $model*/
        $model = Model('order_refund');
        //查询条件
        $condition = array();
        if (isset($_GET['search_sn']) && $_GET['search_sn']) {
            $condition['order_sn'] = $_GET['search_sn'];
        }
        if (isset($_GET['search_phone']) && $_GET['search_phone']) {
            $condition['member_phone'] = $_GET['search_phone'];
        }
        $time_from = strtotime($_GET['search_stime']);
        $time_to = strtotime($_GET['search_etime']);
        if ($time_from && $time_to) {
            $time_to = $time_to + 86400;
            $condition['addtimes'] = array('between',array($time_from,$time_to));
        } elseif ($time_from) {
            $condition['addtimes'] = array('egt',$time_from);
        } elseif ($time_to) {
            $time_to = $time_to + 86400;
            $condition['addtimes'] = array('elt',$time_to);
        }
        if (isset($_GET['search_status']) && is_numeric($_GET['search_status'])) {
            $condition['status'] = intval($_GET['search_status']);
        }
        if (isset($_GET['order_type']) && is_numeric($_GET['order_type'])) {
            $condition['pay_type'] = intval($_GET['order_type']);
        }
        $merchant_id = intval($this->admin_info['merchant_id']);
        if($merchant_id>0){
            $condition['merchant_id'] = $merchant_id;
        }
        $orderList = $model->getOrderRefundListPage($condition,'*', 10);
        Tpl::output('orders', $orderList);
        Tpl::output('pay_type',$model->pay_type);
        Tpl::output('status',$model->status);
        Tpl::output('search', $_GET);
        Tpl::output('page',$model->showpage());
        Tpl::showpage('order_refund.index');
    }

    /**
     * 导出订单
     */
    public function exportOp(){
        /* @var order_refundModel $model*/
        $model = Model('order_refund');
        //查询条件
        $condition = array();
        if (isset($_GET['search_sn']) && $_GET['search_sn']) {
            $condition['order_sn'] = $_GET['search_sn'];
        }
        if (isset($_GET['search_phone']) && $_GET['search_phone']) {
            $condition['member_phone'] = $_GET['search_phone'];
        }
        $time_from = strtotime($_GET['search_stime']);
        $time_to = strtotime($_GET['search_etime']);
        if ($time_from && $time_to) {
            $time_to = $time_to + 86400;
            $condition['addtimes'] = array('between',array($time_from,$time_to));
        } elseif ($time_from) {
            $condition['addtimes'] = array('egt',$time_from);
        } elseif ($time_to) {
            $time_to = $time_to + 86400;
            $condition['addtimes'] = array('elt',$time_to);
        }
        if (isset($_GET['search_status']) && is_numeric($_GET['search_status'])) {
            $condition['status'] = intval($_GET['search_status']);
        }
        if (isset($_GET['pay_type']) && is_numeric($_GET['pay_type'])) {
            $condition['pay_type'] = intval($_GET['pay_type']);
        }
        $merchant_id = intval($this->admin_info['merchant_id']);
        if($merchant_id>0){
            $condition['merchant_id'] = $merchant_id;
        }
        //每个EXCEL最大条数
        $exportSize = 1000;
        if (!is_numeric($_GET['curpage'])) {
            $count = $model->getOrderRefundCount($condition);
            $array = array();
            if ($count > $exportSize) {
                $page = ceil($count / $exportSize);
                for ($i=1; $i<=$page; $i++){
                    $limit1 = ($i -1 ) * $exportSize + 1;
                    $limit2 = $i * $exportSize > $count ? $count : $i * $exportSize;
                    $array[$i] = $limit1 . ' ~ ' . $limit2 ;
                }
                Tpl::output('list',$array);
                Tpl::showpage('export.excel');
            } else {
                $data = $model
                    ->where($condition)
                    ->order('id desc')
                    ->limit($exportSize)
                    ->select();

                $this->createExcel($data, $model->status ,$model->pay_type);
            }
        } else {
            $limit1 = ($_GET['curpage'] - 1) * $exportSize;
            $limit2 = $exportSize;
            $data = $model
                ->where($condition)
                ->order('id desc')
                ->limit("$limit1,$limit2")
                ->select();

            $this->createExcel($data, $model->status,$model->pay_type);
        }

    }

    /**
     * 退款订单订单详细
     */
    public function detailOp()
    {
        $id = intval($_GET['id']);
        /* @var order_refundModel $model */
        $model = Model('order_refund');
        if($id>0){
            $order_info = $model->getOrderRefundInfo(array('id'=>$id));
            if($order_info && is_array($order_info)){
                if($order_info['pic_1']){
                    $order_info['pic_1'] = UPLOAD.'comment/'.$order_info['pic_1'];
                }
                if($order_info['pic_2']){
                    $order_info['pic_2'] = UPLOAD.'comment/'.$order_info['pic_2'];
                }
                if($order_info['pic_3']){
                    $order_info['pic_3'] = UPLOAD.'comment/'.$order_info['pic_3'];
                }
            }
            Tpl::output('pay_type',$model->pay_type);
            Tpl::output('status',$model->status);
            Tpl::output('order',$order_info);
        }
        Tpl::showpage('order.refund.detail');
    }

    /**
     * ajax 获取订单信息
     *
     */
    public function ajax_detailOp()
    {
        $id = intval($_POST['id']);
        /* @var order_refundModel $model */
        $model = Model('order_refund');
        if($id>0){
            $order_info = $model->getOrderRefundInfo(array('id'=>$id));
            if($order_info && is_array($order_info)){
                if($order_info['pic_1']){
                    $order_info['pic_1'] = UPLOAD.'comment/'.$order_info['pic_1'];
                }
                if($order_info['pic_2']){
                    $order_info['pic_2'] = UPLOAD.'comment/'.$order_info['pic_2'];
                }
                if($order_info['pic_3']){
                    $order_info['pic_3'] = UPLOAD.'comment/'.$order_info['pic_3'];
                }
                exit(json_encode($order_info));
            }

        }

    }

    /**
     * 审核退款订单
     */
    public function audit_refundOp()
    {
        $refund_id = intval($_POST['refund_id']);
        $status = intval($_POST['status']);
        $replay = trim($_POST['replay']);
        /* @var order_refundModel $model*/
        $model = Model('order_refund');
        /* @var orderModel $order_model*/
        $order_model = Model('order');
        if($refund_id>0){
            $order_info = $model->getOrderRefundInfo(array('id'=>$refund_id));
            if($order_info && is_array($order_info)){
                if($status==1){
                    if($order_info['pay_type']==1){

                            //微信退款
                            $result = $this->wxRefund($order_info);

                            if(($result['return_code']=='SUCCESS') && ($result['result_code']=='SUCCESS')){
                                //退款成功   //同意退款操作  修改订单状态以及退款订单的状态
                                $res =$model->updateOrderRefund(array('id'=>$refund_id),array('status'=>1,'audittime'=>time(),'replay'=>$replay,'if_pay'=>1,'refund_sn'=>$result['refund_id'],'true_money'=>$result['total_fee']%100));
                                $res2 = $order_model->updateOrder(array('order_id'=>$order_info['order_id']),array('order_status'=>32));
                                if($res && $res2){
                                    $this->log('审核退款订单'.'[订单号:'.$order_info['order_sn'].']',1);
                                    exit(json_encode(array('res'=>1)));
                                }
                            }else if(($result['return_code']=='FAIL') || ($result['result_code']=='FAIL')){
                                //退款失败
                                //原因
                                $reason = (empty($result['err_code_des'])?$result['return_msg']:$result['err_code_des']);
                                exit(json_encode(array('res'=>0,'_msg'=>$reason)));
                            }else{
                                 //失败
                                exit(json_encode(array('res'=>0,'_msg'=>'操作失败')));
                            }

                       }elseif($order_info['pay_type']==2){
                            //支付宝退款 待完善
                        $result = $this->alipayRefund($order_info['out_refund_no'],$order_info['pay_sn'],$order_info['refund_money']);
                        if($result['code']==10000 && $result['msg'] =='Success'){
                            //退款成功
                            $res = $model->updateOrderRefund(array('id'=>$refund_id),array('status'=>1,'audittime'=>time(),'replay'=>$replay,'if_pay'=>1,'refund_sn'=>$result['buyer_logon_id'],'true_money'=>$result['refund_fee']));
                            $res2 = $order_model->updateOrder(array('order_id'=>$order_info['order_id']),array('order_status'=>32));
                            if($res && $res2){
                                $this->log('审核退款订单'.'[订单号:'.$order_info['order_sn'].']',1);
                                exit(json_encode(array('res'=>1)));
                            }else{
                                exit(json_encode(array('res'=>0,'_msg'=>'更改数据库失败')));
                            }
                        }else{
                            exit(json_encode(array('res'=>0,'_msg'=>$result['sub_msg'])));
                        }
                    }
                }else{
                    //拒绝操作
                    if($model->updateOrderRefund(array('id'=>$refund_id),array('status'=>2,'audittime'=>time(),'replay'=>$replay))){
                        $this->log('审核退款订单'.'[订单号:'.$order_info['order_sn'].']',1);
                        exit(json_encode(array('res'=>1)));
                    }else{
                        exit(json_encode(array('res'=>0,'_msg'=>'操作失败')));
                    }
                }
            }
        }

    }


    /**
     * 微信退款
     * @param  array $order_info 订单信息
     * @return 成功时返回(array类型)，其他抛异常
     */
   public function wxRefund($order_info){
        require_once BASE_DATA_PATH."/vendors/weixin/lib/WxPay.Api.php";


        $merchid = WxPayConfig::MCHID;

        $input = new WxPayRefund();
        $input->SetOut_trade_no($order_info['order_sn']);         //自己的订单号
        $input->SetTransaction_id($order_info['pay_sn']);     //微信官方生成的订单流水号，在支付成功中有返回
        $input->SetOut_refund_no($order_info['out_refund_no']);         //退款单号
        $input->SetTotal_fee(intval($order_info['refund_money']*100));         //订单标价金额，单位为分
        $input->SetRefund_fee(intval($order_info['refund_money']*100));            //退款总金额，订单总金额，单位为分，只能为整数
        $input->SetOp_user_id($merchid);
        $result = WxPayApi::refund($input); //退款操作

        // 这句file_put_contents是用来查看服务器返回的退款结果 测试完可以删除了
        //file_put_contents(APP_ROOT.'/Api/wxpay/logs/log3.txt',arrayToXml($result),FILE_APPEND);
        return $result;
    }

    /**
     * 支付宝退货处理
     * 退货前提是必须支付成功
     * @param string $out_trade_no 订单号
     * @param string $wepay_serial
     * @param $totalFee 金额
     */
    public function alipayRefund($out_trade_no,$wepay_serial,$totalFee) {

        require_once BASE_DATA_PATH.'/vendors/alipay/AopClient.php';
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018011101773187';
        $aop->rsaPrivateKey = 'MIIEowIBAAKCAQEAm1P3EZY8AjvdMs0ltJSObEJQIX6EJDxKydOiOeJAodnHqhHtkWAUNeL7YW0klo7ZVJnEdEdxjzjOWpjQHJNgxYLpOCAwTyqOkzmWjWJpLebl2cOQc9mi9DLSMSDb0A4berU+HG7sAcPDUKXWriTbFlnfKtY7pJv0fmyFQiNkJmVEm3Jfuwk9S43MOtHG/e4upw1I2vpZZTg+xEN2NW5vMtug+jHMim4h34/qQno9a+xF0rKJFpYpBa/iF0Au/vyTBgkaD3M1W8niguUlje0QHCbQGvSghoH6htMXTN88aY8Mo2BRGNrFw64r6C+w7kv/pKARIkd3JChJNSolG/tNQwIDAQABAoIBAA326ouGOjbpMuXSU8V8ZaGOBK4+NZscYIzsnfUeRjlG3xCHNBiRzr9ZfMgxi8yNYzSb7nGVyrvZm5PBkVRAW77mGhmVq0IyzUanMsXbRyF9VMTTNDV2J5RUzVjlX13BJu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->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAitkV3HWbV9DUqDRPncMnwc0J4zFehoaWzeMtD2ktpMXO/EqcETgmL62hAdKzfFBDuRQ4pOovlFCXPV5PBRwLdcJL3XXdDnem1cPt4dfbAlpfhi+Q31Fkkv97rV56SRIkbBVIRx4PMVr8+Xbk0KPzF+TlxJrCFgxok2fwO7d2izdefH2BR0UMJ7q8r3cllMe7LwTy6tFwa0LnUap0liBRLTBGuU5lNIQTtnjxjjOkfHJ9GpjnHsmbecFADsFPj2sruDr+lT86QBqVfiAs6KBiTYgV+zyW95uBSWD14+jhG7OAZQvEiPsri4ZXiAViSDBRg/KR2DAdOvCu8Ek0mINFLQIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new AlipayTradeRefundRequest();
        $bizcontent = json_encode([
            'out_trade_no'=>$out_trade_no,
            'trade_no'=> $wepay_serial,
            'refund_amount'=> $totalFee,
            'refund_reason'=>'正常退款'
        ]);
        $request->setBizContent($bizcontent);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        //$resultCode = $result->$responseNode->code;
        $result = object_array($result->$responseNode);
        return $result;
        /*echo $resultCode;
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "退款成功";
        } else {
            echo "退款失败";
        }*/
    }


    /**
     * 创建Excel
     * @param array $data
     * @param array $status
     * @param array $type
     */
    private function createExcel($data, $status,$type) {
        import('libraries.excel');
        $excel_obj = new Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id'=>'s_title','Font'=>array('FontName'=>'宋体','Size'=>'12','Bold'=>'1')));
        //表头
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'订单号');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'手机');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'退款理由');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'退款金额');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'订单支付方式');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'退款支付单号');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'处理状态');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'申请时间');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'处理时间');
        //数据
        foreach ((array)$data as $k=>$v){
            $tmp = array();
            $tmp[] = array('data'=>$v['order_sn']);
            $tmp[] = array('data'=>$v['member_phone']);
            $tmp[] = array('data'=>$v['refund_type']);
            $tmp[] = array('data'=>ncPriceFormat($v['refund_money']));
            $tmp[] = array('data'=>$type[$v['pay_type']]);
            $tmp[] = array('data'=>$v['refund_sn']);
            $tmp[] = array('data'=>$status[$v['status']]);
            $tmp[] = array('data'=>date('Y-m-d H:i:s',$v['addtimes']));
            $tmp[] = array('data'=>date('Y-m-d H:i:s',$v['audittime']));
            $excel_data[] = $tmp;
        }

        $excel_data = $excel_obj->charset($excel_data,CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset('退款订单',CHARSET));
        $excel_obj->generateXML($excel_obj->charset('退款订单',CHARSET).$_GET['curpage'].'-'.date('Y-m-d-H',time()));
    }
}